package org.tech4j.common.core.sign.extractor;

import com.google.common.net.HttpHeaders;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Triple;
import org.tech4j.common.core.constant.Constants;
import org.tech4j.common.core.sign.api.SignParameters;
import org.tech4j.common.core.sign.extractor.parse.ParseDataFactory;
import org.tech4j.common.core.request.param.ParamTypeEnum;

import java.net.URI;
import java.util.Map;
import java.util.Objects;

/**
 * @program: tech4j-common
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/2 19:52
 **/
public class VersionTwoExtractor implements SignParameterExtractor {
    public static final String VERSION_2 = "2.0.0";
    @Override
    public SignParameters extract(HttpServletRequest request) {
        return this.extract(request, ParamTypeEnum.HEADER.getType(), HttpHeaders.AUTHORIZATION);
    }

    @Override
    public SignParameters extract(HttpServletRequest request, String paramType, String paramKey) {
        Triple<Map<String, Object>, String, String> triple = ParseDataFactory.parse(paramType, paramKey, request);
        if (Objects.isNull(triple) || isEmpty(triple.getLeft()) || StringUtils.isBlank(triple.getRight()) || StringUtils.isBlank(triple.getMiddle())) {
            return new SignParameters();
        }
        Map<String, Object> paramMap = triple.getLeft();
        String signature = triple.getMiddle();
        String parameters = triple.getRight();
        SignParameters signParameters = new SignParameters(
                VERSION_2,
                (String) paramMap.get(Constants.APP_KEY),
                (String) paramMap.get(Constants.TIMESTAMP),
                signature,
                URI.create(request.getRequestURI()),
                (String) paramMap.get("alg"));
        signParameters.setParameters(parameters);
        return signParameters;
    }

    protected boolean isEmpty(Map<?, ?> map) {
        return map == null || map.isEmpty();
    }
}
